<template>
  <div class="role">
    <section class="query-form">
      <el-form :inline="true" :model="queryForm" ref="queryForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="queryForm.roleName" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </section>
    <section class="base-table">
      <div class="action">
        <el-button type="primary" @click="handleAdd">创建</el-button>
      </div>
      <el-table :data="roleList">
        <el-table-column
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :formatter="column.formatter"
          v-for="column in columns"
          :key="column.prop"
        ></el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button size="mini" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="primary"
              @click="handleOpenPermission(scope.row)"
              >设置权限</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDelete(scope.row._id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :total="pager.total"
        :page-size="pager.pageSize"
        @current-change="handleCurrentChange"
      />
    </section>
    <el-dialog title="菜单新增" v-model="showModal">
      <el-form
        :model="roleForm"
        label-width="100px"
        :rules="roleFormRules"
        ref="roleFormRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :rows="2"
            v-model="roleForm.remark"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 权限弹框 -->
    <el-dialog title="权限设置" v-model="showPermission">
      <el-form :model="roleForm" label-width="100px">
        <el-form-item label="角色名称">
          {{ curRoleName }}
        </el-form-item>
        <el-form-item label="选择权限">
          <el-tree
            ref="permissionRef"
            default-expand-all
            :data="menuList"
            show-checkbox
            node-key="_id"
            :props="{ label: 'menuName' }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPermission = false">取消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import utils from '../utils/utils'
export default {
  name: 'Role',
  data() {
    return {
      queryForm: {
        roleName: ''
      },
      columns: [
        {
          label: '角色名称',
          prop: 'roleName'
        },
        {
          label: '备注',
          prop: 'remark'
        },
        {
          label: '权限列表',
          prop: 'permissionList',
          width: 200,
          formatter: (row, column, value) => {
            const names = []
            let list = value.halfCheckedKeys || []
            list.map((key) => {
              const name = this.actionMap[key]
              if (key && name) {
                names.push(name)
              }
            })

            return names.join(',')
          }
        },
        {
          label: '创建时间',
          prop: 'createTime',
          formatter(row, column, value) {
            return utils.formatDate(new Date(value))
          }
        },
        {
          label: '更新时间',
          prop: 'updateTime',
          formatter(row, column, value) {
            return utils.formatDate(new Date(value))
          }
        }
      ],
      actionMpa: {},
      roleForm: {},
      showModal: false,
      roleFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称'
          }
        ]
      },
      roleList: [],
      pager: { total: 0, pageSize: 10 },
      showPermission: false,
      curRoleName: '',
      curRoleId: '',
      menuList: []
    }
  },
  mounted() {
    this.getRolesList()

    this.getMenuList()
  },
  methods: {
    async handlePermissionSubmit() {
      const nodes = this.$refs.permissionRef.getCheckedNodes()
      const halfKeys = this.$refs.permissionRef.getHalfCheckedKeys()

      const checkedKeys = []
      const parentKeys = []
      nodes.map((node) => {
        if (!node.children) {
          checkedKeys.push(node._id)
        } else {
          parentKeys.push(node._id)
        }
      })

      let params = {
        _id: this.curRoleId,
        permissionList: {
          checkedKeys,
          halfCheckedKeys: parentKeys.concat(halfKeys)
        }
      }
      await this.$api.updatePermission(params)
      this.showPermission = false
      this.$message.success('设置成功')
      this.getRolesList()
    },
    handleOpenPermission(row) {
      this.curRoleId = row._id
      this.curRoleName = row.roleName
      this.showPermission = true

      let { checkedKeys } = row.permissionList

      setTimeout(() => {
        this.$refs.permissionRef.setCheckedKeys(checkedKeys)
      })
    },
    async getMenuList() {
      const list = await this.$api.getMenuList()
      this.menuList = list

      this.getActionMap(list)
    },
    getActionMap(list) {
      const actionMap = {}

      const deep = (arr) => {
        while (arr.length) {
          let item = arr.pop()
          if (item.children && item.action) {
            actionMap[item._id] = item.menuName
          }
          if (item.children && !item.actoin) {
            deep(item.children)
          }
        }
      }

      deep(JSON.parse(JSON.stringify(list)))
      this.actionMap = actionMap
    },
    async getRolesList() {
      const { list, page } = await this.$api.getRolesList({
        ...this.queryForm,
        ...this.pager
      })
      this.roleList = list
      this.pager.total = page.total
    },
    handleQuery() {
      this.getRolesList()
    },
    handleReset(form) {
      this.$refs[form].resetFields()
    },
    async handleDelete(_id) {
      await this.$api.menuSubmit({ _id, action: 'delete' })
      this.$message.success('删除成功')
      this.getRolesList()
    },
    handleAdd() {
      this.action = 'create'
      this.showModal = true
    },
    handleEdit(row) {
      this.action = 'edit'
      this.showModal = true
      this.$nextTick(() => {
        this.roleForm = {
          roleName: row.roleName,
          remark: row.remark,
          _id: row._id
        }
      })
    },
    async handleDelete(_id) {
      await this.$api.rolesOperate({ _id, action: 'delete' })
      this.$message.success('删除成功')
      this.getRolesList()
    },
    handleClose() {
      this.showModal = false
      this.handleReset('roleFormRef')
    },
    handleSubmit() {
      this.$refs.roleFormRef.validate(async (valid) => {
        if (valid) {
          const { roleForm, action } = this
          const params = { ...roleForm, action }
          const res = await this.$api.rolesOperate(params)
          if (res) {
            this.showModal = false
            this.$message.success('操作成功')
            this.handleReset('roleFormRef')
            this.getRolesList()
          }
        }
      })
    },
    handleCurrentChange(current) {
      this.pager.pageNum = current
      this.getRolesList()
    }
  }
}
</script>

<style lang="scss" scoped></style>
